﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;
using ProgNetComponentsDx.Enums;
using ProgNetComponentsDx.Data;
using ProgNetComponents.Data;

namespace ProgNetComponentsDx.Forms
{
    public partial class BaseSqlCeGridForm : XtraForm
    {
        protected string ValidationMessage;

        public BaseSqlCeGridForm()
        {
            InitializeComponent();
        }
        
        protected virtual bool Save()
        {
            return selectDataProvider1.UpdateDataSet();
        }
        protected virtual void FinishEdit()
        {
            if (modeProvider1.CurrentMode == FormMode.Read ||
                modeProvider1.CurrentMode == FormMode.View)
                return;

            if (gcMain.FocusedView != null)
            {
                gcMain.FocusedView.CloseEditor();
                gcMain.FocusedView.UpdateCurrentRow();
            }
        }
        protected virtual void SaveClick()
        {
            if (ValidateAll())
            {
                if (Save())
                {
                    modeProvider1.CurrentMode = FormMode.Read;
                    changeDetectorProvider1.ResetAll();
                }
                else
                {
                    this.ShowDxErrorDialog("Błąd zapisu!");
                }
            }
            else
            {
                if (ValidationMessage.IsNull())
                    ValidationMessage = "Błąd validacji.";

                this.ShowDxErrorDialog(ValidationMessage);
            }
        }
        protected virtual void EditClick()
        {
            if (modeProvider1.CurrentMode == FormMode.Read)
            {
                modeProvider1.CurrentMode = FormMode.Edit;
            }
            else
            {
                if (changeDetectorProvider1.HasChanges)
                {
                    DialogResult res = this.ShowDxYNCQuestionDialog("Zapisać zmiany?");
                    if (res == System.Windows.Forms.DialogResult.No)
                    {
                        selectDataProvider1.GetSettings(this).DataSet.RejectChanges();
                        modeProvider1.CurrentMode = FormMode.Read;
                        changeDetectorProvider1.ResetAll();
                    }
                    else if (res == System.Windows.Forms.DialogResult.Yes)
                    {
                        SaveClick();
                    }
                }
                else
                {
                    modeProvider1.CurrentMode = FormMode.Read;
                }
            }
        }
        protected virtual void RefreshClick()
        {
            if (!GetRecords())
                this.ShowDxErrorDialog("Błąd czytania danych!");
        }
        protected virtual bool ValidateAll()
        {
            bool result = false;
            ValidationMessage = "";
            result = modeProvider1.ValidateRequiredColumns(ref ValidationMessage);
            return result;
        }
        
        protected virtual void OnContextChanged()
        {
            if (!this.IsDesignMode())
            {
                if (changeDetectorProvider1.HasChanges)
                {
                    if (!Text.EndsWith(" *"))
                        Text += " *";
                    modeProvider1.GetSettings(bbiSave).ReadOnlyModes = FormMode.Read | FormMode.View;
                }
                else
                {
                    if (Text.EndsWith(" *"))
                        Text = Text.Substring(0, Text.Length - 2).Trim();
                    modeProvider1.GetSettings(bbiSave).ReadOnlyModes = FormMode.All;
                }
            }
        }
        protected virtual bool GetRecords()
        {
            bool result = selectDataProvider1.FillDataSet();
            if (result)
            {
                changeDetectorProvider1.ResetAll();
            }
            return result;
        }
        protected virtual void OnLoad()
        {
            if (!GetRecords())
                this.ShowDxErrorDialog("Błąd czytania danych!");
            modeProvider1.CurrentMode = FormMode.Edit;
        }
        
        protected virtual bool CanDeleteRow(DataRow row)
        {
            if (row.RowState == DataRowState.Added)
                return true;
            DataManager m = SelectDataCache.GetManager(selectDataProvider1.GetSettings(this).SelectDataId);
            if (m != null)
                return !m.SchemaChecker.IsRecordUsed(row);
            return true;
        }

        private void bbiRefresh_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            RefreshClick();
        }

        private void bbiSave_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            FinishEdit();
            SaveClick();
        }

        private void bbiEdit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            FinishEdit();
            EditClick();
        }

        private void changeDetectorProvider1_ContextChanged(object sender, EventArgs e)
        {
            OnContextChanged();
        }
        
        private void BaseSqlCeGridForm_Load(object sender, EventArgs e)
        {
			if(this.IsDesignMode())
			{
				if (layoutProvider1.LayoutName.IsNull())
					layoutProvider1.LayoutName = this.Site.Name;
            } 
			else
				OnLoad();
        }

        void modeProvider1_DeleteRow(object sender, Mode.DeleteRowEventArgs e)
        {
            e.Cancel = !CanDeleteRow(e.Row);
            if (e.Cancel)
                this.ShowDxInfoDialog("Rekord jest używany. Nie można go skasować.");
        }

        private void bbiZapiszLayout_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            layoutProvider1.SaveLayout();
        }

        private void bbiResetLayout_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            layoutProvider1.RestoreDefaultLayout();
        }

        private void bbiReadLayout_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            layoutProvider1.ApplySavedLayout();
        }

    }
}
